package com.paas.demo.controller;

import com.paas.demo.common.PJson;
import com.paas.demo.menu.MenuConfiguration;
import com.paas.demo.shiro.ShiroUser;
import com.paas.demo.shiro.ShiroUserToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ShiroUserController {

    private static final Logger log = LoggerFactory.getLogger(ShiroUserController.class);
    @Autowired
    private MenuConfiguration menuConfig;
    /**
     * 登录接口，由于UserService中是模拟返回用户信息的，
     * 所以用户名随意，密码123456
     *
     * @return
     */
    @GetMapping("/app/v1/login")
    public PJson login(@RequestParam(name= "uname",required = true)String uname, @RequestParam(name= "pwd",required = true)String pwd, boolean remember){

        String oper = "user login";

        if (StringUtils.isEmpty(uname)){
            return PJson.fail(oper,"用户名不能为空");
        }
        if (StringUtils.isEmpty(pwd)){
            return PJson.fail(oper,"密码不能为空");
        }

        Subject currentUser = SecurityUtils.getSubject();
        try {
            //登录
            currentUser.login( new ShiroUserToken(uname, pwd, remember, ShiroUserToken.TokenType.sys) );
            //从session取出用户信息
            ShiroUser user = (ShiroUser) currentUser.getPrincipal();
            if (user==null) throw new AuthenticationException();

            log.info("currentUser session = " + currentUser.getSession().getId());

            //返回登录用户的信息给前台，含用户的所有角色和权限
            return PJson.succ(oper)
                    .data("uid",user.getUid())
                    .data("nick",user.getNick())
                    .data("roles",user.getRoles())
                    .data("perms",user.getPerms());

        } catch ( UnknownAccountException uae ) {
            log.warn("用户帐号不正确");
            return PJson.fail(oper,"用户帐号或密码不正确");

        } catch ( IncorrectCredentialsException ice ) {
            log.warn("用户密码不正确");
            return PJson.fail(oper,"用户帐号或密码不正确");

        } catch ( LockedAccountException lae ) {
            log.warn("用户帐号被锁定");
            return PJson.fail(oper,"用户帐号被锁定不可用");

        } catch ( AuthenticationException ae ) {
            log.warn("登录出错");
            return PJson.fail(oper,"登录失败："+ae.getMessage());
        }

    }
    @GetMapping("/config")
    public Object configurationProperties() {

        return menuConfig;
    }
}
